﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.XtraCharts.Web;
using DevExpress.XtraCharts;

namespace TireService.Web.UserControls.StatusOverview
{
    public partial class ucCustomerPipelineOverview : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                TireServiceDB db = new TireServiceDB();

                // Show default start and end of present month
                txtStartDate.Value = "01-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
                txtEndDate.Value = Convert.ToDateTime("01-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString()).AddMonths(1).AddDays(-1).Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();

                BindCustomerPipelineData(db, Convert.ToDateTime(txtStartDate.Value), Convert.ToDateTime(txtEndDate.Value));
            }
        }

        /// <summary>
        /// Bind chart data
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="ServiceCarId">Id on service car</param>
        /// <param name="Startdate">Startdate for data to show in chart</param>
        private void BindCustomerPipelineData(TireServiceDB db, DateTime Startdate, DateTime Enddate)
        {
            CreateCustomerPortfolioSerie(db, Startdate, Enddate);

            CreateCustomerInActive(db, Startdate, Enddate);

            CreateCustomerNew(db, Startdate, Enddate);
        }

        public class CustomerPipelineCount
        {
            public DateTime CountDate { get; set; }
            public int CustomerCount { get; set; }
        }

        private void CreateCustomerPortfolioSerie(TireServiceDB db, DateTime Startdate, DateTime Enddate) 
        {
            // Add first series - Customer Portfolio
            // Create an empty Bar series and add it to the chart.
            Series series = new Series("Aktive kunder", ViewType.Line);
            chartCustomerPipeline.Series.Add(series);

            ((PointSeriesView)series.View).PointMarkerOptions.Size = 2;
            series.Label.Visible = false;

            List<CustomerPipelineCount> customerportfolio = new List<CustomerPipelineCount>();

            // Generate dates based on selected period
            for (DateTime date = Startdate; Enddate.CompareTo(date) > 0; date = date.AddDays(1))
            {
                int Count = db.CustomerSubscriptions.Where(p => p.Createdate <= date & (p.InActiveDate == null | p.InActiveDate > date)).Count();

                CustomerPipelineCount customercount = new CustomerPipelineCount();
                customercount.CountDate = date;
                customercount.CustomerCount = Count;
                customerportfolio.Add(customercount);
            }

            // Generate a data table and bind the series to it.
            series.DataSource = customerportfolio;

            // Specify data members to bind the series.
            series.ArgumentScaleType = ScaleType.DateTime;
            series.ArgumentDataMember = "CountDate";
            series.ValueScaleType = ScaleType.Numerical;
            series.ValueDataMembers.AddRange(new string[] { "CustomerCount" });
        }

        private void CreateCustomerInActive(TireServiceDB db, DateTime Startdate, DateTime Enddate)
        {
            // Add first series - Customer Portfolio
            // Create an empty Bar series and add it to the chart.
            Series series = new Series("Opsagte kunder", ViewType.Bar);
            chartCustomerPipeline.Series.Add(series);

            List<CustomerPipelineCount> customerportfolio = new List<CustomerPipelineCount>();

            // Generate dates based on selected period
            for (DateTime date = Startdate; Enddate.CompareTo(date) > 0; date = date.AddDays(1))
            {
                int Count = db.CustomerSubscriptions.Where(p => p.InActiveDate == date & p.InActive == true).Count();

                if (Count > 0)
                {
                    CustomerPipelineCount customercount = new CustomerPipelineCount();
                    customercount.CountDate = date;
                    customercount.CustomerCount = (-1 * Count);
                    customerportfolio.Add(customercount);    
                }
            }

            // Generate a data table and bind the series to it.
            series.DataSource = customerportfolio;

            // Specify data members to bind the series.
            series.ArgumentScaleType = ScaleType.DateTime;
            series.ArgumentDataMember = "CountDate";
            series.ValueScaleType = ScaleType.Numerical;
            series.ValueDataMembers.AddRange(new string[] { "CustomerCount" });
        }

        private void CreateCustomerNew(TireServiceDB db, DateTime Startdate, DateTime Enddate)
        {
            // Add first series - Customer Portfolio
            // Create an empty Bar series and add it to the chart.
            Series series = new Series("Nye kunder", ViewType.Bar);
            chartCustomerPipeline.Series.Add(series);

            List<CustomerPipelineCount> customerportfolio = new List<CustomerPipelineCount>();

            // Generate dates based on selected period
            for (DateTime date = Startdate; Enddate.CompareTo(date) > 0; date = date.AddDays(1))
            {
                int Count = db.CustomerSubscriptions.Where(p => DateTime.Compare(p.Createdate.Date, date.Date) == 0).Count();

                if (Count > 0)
                {
                    CustomerPipelineCount customercount = new CustomerPipelineCount();
                    customercount.CountDate = date;
                    customercount.CustomerCount = Count;
                    customerportfolio.Add(customercount);    
                }
            }

            // Generate a data table and bind the series to it.
            series.DataSource = customerportfolio;

            // Specify data members to bind the series.
            series.ArgumentScaleType = ScaleType.DateTime;
            series.ArgumentDataMember = "CountDate";
            series.ValueScaleType = ScaleType.Numerical;
            series.ValueDataMembers.AddRange(new string[] { "CustomerCount" });
        }

        /// <summary>
        /// Callback function that refreshes Chart
        /// </summary>
        protected void chartCustomerPipeline_CustomCallback(object sender, CustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // Get values (0: Startdate, 1: Enddate)
            string[] param = e.Parameter.Split('|');

            DateTime Startdate = Convert.ToDateTime(param[0]);
            DateTime Enddate = Convert.ToDateTime(param[1]);

            BindCustomerPipelineData(db, Startdate, Enddate);
        }
    }
}